# coding=utf-8
"""
Copyright (c) Huawei Technologies Co., Ltd. 2020-2028. All rights reserved.
Description:
FileName：utils.py.py
Author: h00568282/huangbin 
Create Date: 2025/9/19 11:50
Notes:

"""

import os
import json
from rich.markup import escape
from typing import List

from sys_intd.schema import CustomServerConfig, RemoteServerConfig, ServerConfig, STDIOServerConfig


def print_simple_servers_list(servers: List):
    """Display a simple list of server names.

    Args:
        servers: List of server dictionaries containing server information
    """
    # Sort servers by name for consistent display
    sorted_servers = sorted(servers, key=lambda s: s["name"])

    # Format and print each server name
    for server in sorted_servers:
        name = server["name"]
        console.print(f"[cyan]{name}[/]")



def check_server_name(server_name: str, servers: List[str]) -> str:
    '''
        校验mcp server是否符合mcp center中的命名规划，
        标准：xxx-xxx-server
    Args:
        server_name:
    Returns:
    '''

    server_name = server_name.replace("_", "-")
    if server_name not in servers:
        server_name = f"{server_name}-server"

    return server_name


def extract_python_cmd(service_path: str, service_name: str) -> List[str]:

    all_services = os.listdir(service_path)
    service_name = check_server_name(service_name, all_services)

    service_file = os.path.join(service_path, f"{service_name}.service")
    try:
        with open(service_file, "r") as f:
            service_content = f.readlines()
    except FileNotFoundError as e:
        raise FileNotFoundError(str(e))

    command = ""
    for line in service_content:
        if line.strip().startswith("ExecStart="):
            exec_start = line.strip()
            full_command = exec_start[len("ExecStart="):].strip()
            command = full_command.replace("/usr/bin/python3", "python3")
            break

    excutor_cmd = []
    if command:
        excutor_cmd = command.split(" ")
    return excutor_cmd



def print_server_config(server_config: ServerConfig, is_stashed=False, show_name=True) -> List[str]:
    """Print detailed information about a server configuration.

    Args:
        server_config: Server configuration information
        is_stashed: Whether the server is stashed (affects display style)
        show_name: Whether to show the server name (default True for backwards compatibility)
    """
    output_lines = []
    # Server name and command
    if show_name:
        if is_stashed:
            output_lines.append(f"[bold yellow]{server_config.name}[/] [dim](stashed)[/]")
        else:
            output_lines.append(f"[bold cyan]{server_config.name}[/]")

    if isinstance(server_config, RemoteServerConfig):
        output_lines.append(f"  Url: [green]{server_config.url}[/]")
        headers = server_config.headers
        if headers:
            output_lines.append("  Headers:")
            for key, value in headers.items():
                output_lines.append(f'    [bold blue]{key}[/] = [green]"{value}"[/]')
        output_lines.append("  " + "-" * 50)
        return output_lines
    if isinstance(server_config, CustomServerConfig):
        output_lines.append("  Type: [green]Custom[/]")
        output_lines.append("  " + "-" * 50)
        output_lines.append("  Config:")
        output_lines.append(json.dumps(server_config.config, indent=2))
        output_lines.append("  " + "-" * 50)
        return output_lines

    # Handle STDIOServerConfig - all remaining configs should be STDIO
    if not isinstance(server_config, STDIOServerConfig):
        output_lines.append("  Type: [red]Unknown server type[/]")
        output_lines.append("  " + "-" * 50)
        return output_lines

    command = server_config.command
    output_lines.append(f"  Command: [green]{command}[/]")

    # Display arguments
    args = server_config.args
    if args:
        output_lines.append("  Arguments:")
        for i, arg in enumerate(args):
            output_lines.append(f"    {i}: [yellow]{escape(arg)}[/]")

    # Display environment variables
    env_vars = server_config.env
    if env_vars:
        output_lines.append("  Environment Variables:")
        for key, value in env_vars.items():
            output_lines.append(f'    [bold blue]{key}[/] = [green]"{value}"[/]')
    else:
        output_lines.append("  Environment Variables: [italic]None[/]")

    # Add a separator line between servers
    output_lines.append("  " + "-" * 50)

    return output_lines